﻿using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class DistribusiBarangProposal : System.Web.UI.Page
{
    private static string strConn = ConfigurationManager.ConnectionStrings["LabConnectionString"].ConnectionString;
    private static Font font10 = new Font(Font.COURIER, 10f, Font.NORMAL);
    private static Font font10b = new Font(Font.COURIER, 10f, Font.BOLD);
    private static Font font12 = new Font(Font.COURIER, 12f, Font.NORMAL);
    private static Font font12b = new Font(Font.COURIER, 12f, Font.BOLD);
    private static Font font13b = new Font(Font.COURIER, 13f, Font.BOLD);
    private static Font font14b = new Font(Font.COURIER, 14f, Font.BOLD);

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            populateTahunAnggaran();
            populatePeneliti();
        }
        cetakProposalPDF();
    }

    private void populateList1()
    {
        //sp_persetujuan_list1 2017
        if (string.IsNullOrEmpty(lstTahun.SelectedValue))
        {
            return;
        }

        DataTable dt = new DataTable();
        using (SqlDataAdapter da = new SqlDataAdapter(string.Format("sp_distribusi_list1 {0}, {1} ", lstTahun.SelectedValue.ToString(), lstPeneliti.SelectedValue.ToString()), strConn))
        {
            da.Fill(dt);
        }
        userList.DataSource = dt;
        userList.DataBind();
        //btnSetuju.Enabled = dt.Rows.Count > 0;

        if (dt.Rows.Count < 1)
        {
            showMessage("Tidak ada data", "Tidak ada daftar proposal", "success");
        }
    }

    private void populateList2()
    {
        //sp_persetujuan_list2 2017
        if (string.IsNullOrEmpty(lstTahun.SelectedValue))
        {
            return;
        }

        DataTable dt = new DataTable();
        using (SqlDataAdapter da = new SqlDataAdapter("sp_distribusi_list2 " + lstTahun.SelectedValue, strConn))
        {
            da.Fill(dt);
        }
        list2.DataSource = dt;
        list2.DataBind();
    }

    private void showMessage(string caption, string message, string type)
    {
        message = message.Replace("'", "&apos;");
        message = message.Replace(Environment.NewLine, "<br />");
        string clientScript = "$(document).ready(function(){ new PNotify({ title: '" + caption + "', text: '" + message + "', type: '" + type + "',styling: 'bootstrap3' }); });";
        ScriptManager.RegisterStartupScript(Page, this.GetType(), "ShowMessage", clientScript, true);
    }

    private void populateTahunAnggaran()
    {
        string query = "sp_get_tahun_anggaran";
        DataTable dt = new DataTable();
        using (SqlDataAdapter da = new SqlDataAdapter(query, strConn))
        {
            da.Fill(dt);
        }
        DataTable tahun = new DataTable();
        tahun.Columns.Add("TAHUN");
        if (dt.Rows.Count > 0)
        {
            DataRow dr = tahun.NewRow();
            dr["TAHUN"] = "";
            tahun.Rows.Add(dr);

            int min = int.Parse(dt.Rows[0]["TAHUN1"].ToString());
            int max = int.Parse(dt.Rows[0]["TAHUN2"].ToString());
            for (int i = min; i <= max; i++)
            {
                dr = tahun.NewRow();
                dr["TAHUN"] = i;
                tahun.Rows.Add(dr);
            }
        }
        lstTahun.DataSource = tahun;
        lstTahun.DataValueField = "TAHUN";
        lstTahun.DataTextField = "TAHUN";
        lstTahun.DataBind();
    }

    private void populatePeneliti()
    {
        string query = "sp_list_peneliti " + Session["idLab"];
        DataTable dt = new DataTable();
        using (SqlDataAdapter da = new SqlDataAdapter(query, strConn))
        {
            da.Fill(dt);
        }
        var dr = dt.NewRow();
        dt.Rows.InsertAt(dr, 0);
        lstPeneliti.DataSource = dt;
        lstPeneliti.DataValueField = "ID";
        lstPeneliti.DataTextField = "NAMA";
        lstPeneliti.DataBind();
    }

    protected void btnProposal_Click(object sender, EventArgs e)
    {
        populateList1();
        populateList2();
    }

    protected void btnDistribusi_Click(object sender, EventArgs e)
    {
        //sp_distribusi_proposal
        Button btn = sender as Button;
        var idProposal = btn.CommandArgument;
        if (string.IsNullOrEmpty(idProposal))
        {
            showMessage("Terjadi Kesalahan", "Silakan pilih proposal yang akan didistribusikan", "error");
            return;
        }

        try
        {
            using (SqlConnection cn = new SqlConnection(strConn))
            {
                cn.Open();
                string query = "sp_distribusi_proposal '{0}', {1}";
                using (SqlCommand cmd = new SqlCommand(string.Format(query, idProposal, Session["idUser"])))
                {
                    cmd.Connection = cn;
                    int ra = cmd.ExecuteNonQuery();
                    if (ra > 0)
                    {
                        populateList1();
                        populateList2();
                        showMessage("Sukses", "Permintaan penelitian berhasil didistribusikan.", "success");

                        //showMessage("Cetak Proposal", "Proposal berhasil dikirim, tunggu beberapa saat hingga proses download selesai.", "success");
                        //success --> cetak
                        ClientScript.RegisterStartupScript(GetType(), "OpenWindow", "setTimeout(function() {window.open('DistribusiBarangProposal.aspx?ppid=" + idProposal + "', '_self'); }, 2000);", true);
                    }
                    else
                    {
                        showMessage("Terjadi Kesalahan", "Tidak ada data yang berhasil ditulis.", "error");
                    }
                }
                cn.Close();
            }
        }
        catch (Exception ex)
        {
            showMessage("Terjadi Kesalahan", "Gagal mengupdate status proposal : " + ex.Message, "error");
        }
    }

    #region PDF

    private void addRowDetailCell(PdfPTable rincianTable, string text, bool isLast = false, bool isNumeric = false)
    {
        rincianTable.AddCell(new PdfPCell(new Phrase(text, font10)) { PaddingTop = 0, PaddingBottom = 5, HorizontalAlignment = isNumeric ? 2 : 0, BorderWidthTop = 0, BorderWidthBottom = 1, BorderWidthLeft = 1, BorderWidthRight = isLast ? 1 : 0 });
    }

    private void addRowGroupCell(PdfPTable rincianTable, string text)
    {
        rincianTable.AddCell(new PdfPCell(new Phrase(text, font10b)) { BackgroundColor = Color.LIGHT_GRAY, Colspan = 5, PaddingTop = 0, PaddingBottom = 5, HorizontalAlignment = 0, BorderWidthTop = 1, BorderWidthBottom = 1, BorderWidthLeft = 1, BorderWidthRight = 1 });
    }

    private void cetakProposalPDF()
    {
        string idProposal = Request.QueryString["ppid"];
        if (string.IsNullOrEmpty(idProposal))
        {
            return;
        }

        DataSet ds = new DataSet();
        using (var da = new SqlDataAdapter("sp_cetak_bon_pengeluaran '" + idProposal + "'", strConn))
        {
            da.Fill(ds);
        }

        if (ds.Tables.Count < 3)
        {
            return;
        }

        DataTable dtHeader = ds.Tables[0];
        DataTable dtKimia = ds.Tables[1];
        DataTable dtPenunjang = ds.Tables[2];

        Document doc = new Document();
        doc.SetPageSize(PageSize.A4);
        doc.SetMargins(50f, 50f, 10f, 10f);
        MemoryStream ms = new MemoryStream();
        var writer = PdfWriter.GetInstance(doc, ms);
        doc.Open();

        PdfPTable allHeaderTable = new PdfPTable(2) { WidthPercentage = 100 };
        int wh1 = (int)(0.1 * PageSize.A4.Width);
        int wh2 = (int)(0.9 * PageSize.A4.Width);
        allHeaderTable.SetWidths(new[] { wh1, wh2 });

        PdfPTable headerTable = new PdfPTable(1);
        headerTable.AddCell(new PdfPCell(new Phrase(dtHeader.Rows[0]["line1"].ToString(), font12b)) { HorizontalAlignment = 1, BorderWidth = 0, PaddingBottom = 5 });
        headerTable.AddCell(new PdfPCell(new Phrase(dtHeader.Rows[0]["line2"].ToString(), font10)) { HorizontalAlignment = 1, BorderWidth = 0 });
        headerTable.AddCell(new PdfPCell(new Phrase(dtHeader.Rows[0]["line3"].ToString(), font12)) { HorizontalAlignment = 1, BorderWidth = 0, PaddingBottom = 5 });
        headerTable.AddCell(new PdfPCell(new Phrase(dtHeader.Rows[0]["line4"].ToString(), font14b)) { HorizontalAlignment = 1, BorderWidth = 0, PaddingBottom = 5 });

        iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(Server.MapPath(".") + @"\images\balitvet.png");
        logo.WidthPercentage = 10;

        allHeaderTable.AddCell(new PdfPCell(logo, true) { BorderWidth = 0 });
        allHeaderTable.AddCell(new PdfPCell(headerTable) { UseBorderPadding = false, BorderWidth = 0 });
        //allHeaderTable.AddCell(new PdfPCell(new Phrase("Bagian : " + dtHeader.Rows[0]["bagian"].ToString(), font12b)) { HorizontalAlignment = 0, BorderWidth = 0, PaddingBottom = 5, Colspan = 2 });

        doc.Add(allHeaderTable);
        PdfPTable rincianTable = new PdfPTable(4) { WidthPercentage = 100 };
        int w1 = (int)(0.08 * PageSize.A4.Width);
        int w2 = (int)(0.42 * PageSize.A4.Width);
        int w3 = (int)(0.2 * PageSize.A4.Width);
        int w4 = (int)(0.3 * PageSize.A4.Width);
        rincianTable.SetWidths(new[] { w1, w2, w3, w4 });

        rincianTable.AddCell(new PdfPCell(new Phrase("No.", font10b)) { PaddingTop = 5, PaddingBottom = 5, HorizontalAlignment = 1, BorderWidthLeft = 1, BorderWidthTop = 1, BorderWidthBottom = 1, BorderWidthRight = 0 });
        rincianTable.AddCell(new PdfPCell(new Phrase("Nama Barang", font10b)) { PaddingTop = 5, PaddingBottom = 5, HorizontalAlignment = 1, BorderWidthLeft = 1, BorderWidthTop = 1, BorderWidthBottom = 1, BorderWidthRight = 0 });
        rincianTable.AddCell(new PdfPCell(new Phrase("Banyaknya", font10b)) { PaddingTop = 5, PaddingBottom = 5, HorizontalAlignment = 1, BorderWidthLeft = 1, BorderWidthTop = 1, BorderWidthBottom = 1, BorderWidthRight = 0 });

        //PdfPTable banyaknyaTable = new PdfPTable(2) { SpacingAfter = 0, SpacingBefore = 0 };
        //banyaknyaTable.AddCell(new PdfPCell(new Phrase("Banyaknya", font10b)) { Colspan = 2, PaddingTop = 5, PaddingBottom = 5, HorizontalAlignment = 1, BorderWidthTop = 0, BorderWidthBottom = 1, BorderWidthLeft = 0, BorderWidthRight = 0 });
        //banyaknyaTable.AddCell(new PdfPCell(new Phrase("Permintaan", font10b)) { PaddingTop = 5, PaddingBottom = 5, HorizontalAlignment = 1, BorderWidthTop = 0, BorderWidthBottom = 0, BorderWidthLeft = 0, BorderWidthRight = 1 });
        //banyaknyaTable.AddCell(new PdfPCell(new Phrase("Diberikan", font10b)) { PaddingTop = 5, PaddingBottom = 5, HorizontalAlignment = 1, BorderWidthTop = 0, BorderWidthBottom = 0, BorderWidthLeft = 0, BorderWidthRight = 0 });
        //rincianTable.AddCell(new PdfPCell(banyaknyaTable) { Colspan = 2, UseBorderPadding = false, BorderWidthLeft = 1, BorderWidthTop = 1, BorderWidthBottom = 1, BorderWidthRight = 0 });
        rincianTable.AddCell(new PdfPCell(new Phrase("Keterangan", font10b)) { PaddingTop = 5, PaddingBottom = 5, HorizontalAlignment = 1, BorderWidthTop = 1, BorderWidthBottom = 1, BorderWidthLeft = 1, BorderWidthRight = 1 });

        if (dtKimia.Rows.Count > 0)
        {
            addRowGroupCell(rincianTable, "Bahan Kimia");
            foreach (DataRow item in dtKimia.Rows)
            {
                addRowDetailCell(rincianTable, item["nomor"].ToString(), false, true);
                addRowDetailCell(rincianTable, item["nama"].ToString());
                addRowDetailCell(rincianTable, item["permintaan"].ToString(), false, true);
                //addRowDetailCell(rincianTable, item["diberikan"].ToString(), false, true);
                addRowDetailCell(rincianTable, item["keterangan"].ToString(), true);
            }
        }

        if (dtPenunjang.Rows.Count > 0)
        {
            addRowGroupCell(rincianTable, "Bahan Penunjang");
            foreach (DataRow item in dtPenunjang.Rows)
            {
                addRowDetailCell(rincianTable, item["nomor"].ToString(), false, true);
                addRowDetailCell(rincianTable, item["nama"].ToString());
                addRowDetailCell(rincianTable, item["permintaan"].ToString(), false, true);
                //addRowDetailCell(rincianTable, item["diberikan"].ToString(), false, true);
                addRowDetailCell(rincianTable, item["keterangan"].ToString(), true);
            }
        }

        doc.Add(rincianTable);

        PdfPTable footerTable = new PdfPTable(3) { WidthPercentage = 100 };
        int fw = (int)(0.33 * PageSize.A4.Width);
        footerTable.SetWidths(new[] { fw, fw, fw });
        footerTable.AddCell(new PdfPCell(new Phrase("Untuk Keperluan : ______________________", font10)) { HorizontalAlignment = 0, BorderWidth = 0, PaddingBottom = 5, PaddingTop = 5, NoWrap = true });
        footerTable.AddCell(new PdfPCell() { BorderWidth = 0, });
        footerTable.AddCell(new PdfPCell(new Phrase("Bogor, " + dtHeader.Rows[0]["tanggal"].ToString(), font10)) { HorizontalAlignment = 1, BorderWidth = 0, PaddingBottom = 5, PaddingTop = 5 });

        footerTable.AddCell(new PdfPCell(new Phrase("Kode Proposal   : " + dtHeader.Rows[0]["kode"].ToString(), font10)) { HorizontalAlignment = 0, BorderWidth = 0, PaddingBottom = 5, PaddingTop = 5 });
        footerTable.AddCell(new PdfPCell() { BorderWidth = 0, });
        footerTable.AddCell(new PdfPCell() { BorderWidth = 0, });

        footerTable.AddCell(new PdfPCell(new Phrase("Yang Meminta", font10)) { HorizontalAlignment = 1, BorderWidth = 0, PaddingBottom = 5 });
        footerTable.AddCell(new PdfPCell(new Phrase("Mengetahui :", font10)) { HorizontalAlignment = 1, BorderWidth = 0, PaddingBottom = 5 });
        footerTable.AddCell(new PdfPCell(new Phrase("Yang Menyerahkan", font10)) { HorizontalAlignment = 1, BorderWidth = 0, PaddingBottom = 5 });

        footerTable.AddCell(new PdfPCell() { BorderWidth = 0, });
        footerTable.AddCell(new PdfPCell(new Phrase("Penanggung Jawab Gudang/Perlengkapan", font10)) { HorizontalAlignment = 1, BorderWidth = 0, PaddingBottom = 5 });
        footerTable.AddCell(new PdfPCell() { BorderWidth = 0, });

        footerTable.AddCell(new PdfPCell() { BorderWidth = 0, });
        footerTable.AddCell(new PdfPCell() { BorderWidth = 0, });
        footerTable.AddCell(new PdfPCell() { BorderWidth = 0, FixedHeight = 25 });

        footerTable.AddCell(new PdfPCell(new Phrase(dtHeader.Rows[0]["nama"].ToString(), font10)) { HorizontalAlignment = 1, BorderWidth = 0, PaddingBottom = 5 });
        footerTable.AddCell(new PdfPCell(new Phrase("(.....................)", font10)) { HorizontalAlignment = 1, BorderWidth = 0, PaddingBottom = 5 });
        footerTable.AddCell(new PdfPCell(new Phrase("(.....................)", font10)) { HorizontalAlignment = 1, BorderWidth = 0, PaddingBottom = 5 });

        doc.Add(footerTable);
        doc.Close();

        Response.Clear();
        //Response.ContentType = "application/pdf";
        Response.ContentType = "application/octet-stream";
        Response.AppendHeader("Content-Disposition", "attachment; filename=proposal_" + dtHeader.Rows[0]["kode"].ToString() + ".pdf");
        Response.BinaryWrite(ms.ToArray());
    }

    #endregion
}